package temp

// todo: 迁移到array目录
// https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
// 算法: 遍历
// min[start][end] = min(min[start][end-1], num[end])
// max[start][end] = max(min[start][end-1], num[end])
// 时间复杂度: O(n^2)
// 当前: 超过时间限制，思考更优方案
func minInt(x, y int) int {
	if x <= y {
		return x
	}
	return y
}

func maxInt(x, y int) int {
	if x >= y {
		return x
	}
	return y
}

func LongestSubarray(nums []int, limit int) int {
	numLen := len(nums)
	maxLen := 0

	for x := 0; x < numLen; x++ {
		minDistance, maxDistance := nums[x], nums[x]
		for y := x; y < numLen; y++ {
			minDistance = minInt(minDistance, nums[y])
			maxDistance = maxInt(maxDistance, nums[y])
			currentSub := maxDistance - minDistance
			if currentSub <= limit {
				currentLen := y - x + 1
				if currentLen > maxLen {
					maxLen = currentLen
				}
			}
		}
	}
	return maxLen
}
